import {
	Encrypt,
	Decrypt
} from "./aes";
import base_url from "./config.js";
import CryptoJS from "crypto-js";
const decryptWhite = []

// 是否加密
const requiredCrypto = false;
// 不加密白名单
const noCrytoList = ["/auth/appLogin"];

export default class Request {

	http(param) {
		// 请求参数
		var url = param.url,
			method = param.method,
			header = {},
			data = {},
			token = param.token || "",
			hideLoading = param.hideLoading || false;
		if (param.data != null) {
			if (requiredCrypto) {
				if (noCrytoList.includes(param.url)) {
					// 不加密
					data = params.data;
				} else {
					data = Encrypt(JSON.stringify(params.data));
				}
			} else {
				data = params.data;
			}
		}
		//拼接完整请求地址
		var requestUrl = base_url + url;

		if (method) {
			method = method.toUpperCase(); //小写改为大写
			if (method == "POST") {
				header = {
					'content-type': "application/x-www-form-urlencoded"
				};
			} else {
				header = {
					'content-type': "application/json"
				};
			}
		}

		//加载圈
		if (!hideLoading) {
			uni.showLoading({
				title: '加载中...'
			});
		}

		// 返回promise
		return new Promise((resolve, reject) => {
			// 请求
			uni.request({
				url: requestUrl,
				data: data,
				method: method,
				header: header,
				success: (res) => {
					if (res.data.code && res.data.code == 401) {
						uni.showToast({
							title: '请登录',
							icon: 'none'
						});
						// 跳转登录
						// uni.reLaunch({
						// 	url:'/pages/login/login'
						// })
						return;
					}
					if (res.data.code && res.data.code != 200) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
						return;
					}
					// if (noCrytoList.includes(url)) {
					//   resolve(res.data);
					// } else {
					//   resolve(JSON.parse(Decrypt(res.data)));
					// }
					resolve(res.data);


				},
				//请求失败
				fail: (e) => {
					uni.showToast({
						title: "" + e.data.msg,
						icon: 'none'
					});
					resolve(e.data);
				},
				//请求完成
				complete() {
					//隐藏加载
					if (!hideLoading) {
						uni.hideLoading();
					}
					resolve();
					return;
				}
			})
		})
	}
}
